/**
 * 科室选择框
 *
 * @author banglong
 * @date 2016/8/19.
 */
define(['Layer', 'text!../html/components/bill/batchDialogTemp.html!strip', 'layPage', 'rootPath', 'avalon', 'tools'],
  function (layer, htmlTemp, laypage, rootPath, avalon, tools) {

    /** @todo 设置路径 */
    laypage.dir = rootPath.getRootPath() + 'js/common/laypage/skin/laypage.css';

    var api; //
    var layeroObj; // 显示框隐藏 不销毁
    var OutDeptAccount = {}; //
    var InputDeptAccount = {}; //
    var chooseGoods; // 物品信息
    var BillStatus;
    var isSend;

    var InputTransferBill; // 保存 方法
    var InputTransferBillError; // 保存失败的回掉

    /**
     * @todo 关闭 layerui 的dialog
     */
    var layeroObjHide = function () {
      layer.close(layeroObj);
    };

    // 定义 科室选择框的 vm对象
    var batchDialogVm;
    var getVmOption = function () {
      return {
        $id: 'batchDialog',
        chooseGoods: [],
        batchList: [],

        clickIndex: 0, // 用于保存上次点击的 index

        hideDialog: function () { // 隐藏选择框
          layeroObjHide();
        },

        handleClick: function (index) { // 单击事件

          if (batchDialogVm.clickIndex !== index) {
            chooseGoods[batchDialogVm.clickIndex].BatchList = JSON.parse(JSON.stringify(batchDialogVm.batchList.$model));
            batchDialogVm.clickIndex = index;
            if (chooseGoods[index].BatchList) {
              batchDialogVm.batchList.splice(0, batchDialogVm.batchList.length);
              batchDialogVm.batchList.pushArray(chooseGoods[index].BatchList);
            }
          }
          batchDialogVm.clickIndex = index;
          // checkApplyCount(chooseGoods); // 监测申请的数量和
        },

        handleSureBtn: function () { // 确定事件 保存
          chooseGoods[batchDialogVm.clickIndex].BatchList = JSON.parse(JSON.stringify(batchDialogVm.batchList.$model));
          if (isSend) {
            saveTransferBill(batchDialogVm, chooseGoods, true);
          } else {
            saveTransferBill(batchDialogVm, chooseGoods, false);
          }
          layeroObjHide();
        },

        handleApplyCountInput: function (e) { // 输入数量的改变事件

          var index = parseInt(e.target.parentNode.getAttribute('data_index'));
          var count = parseInt(batchDialogVm.batchList[index].SelectedCount); //数量
          if (!/^[0-9]*$/.test(batchDialogVm.batchList[index].SelectedCount)) {
            batchDialogVm.batchList[index].SelectedCount = 0;
            return;
          }

          var batch = JSON.parse(JSON.stringify(batchDialogVm.batchList[index].$model)); //
          if (count > batchDialogVm.batchList[index].Counts) {
            count = batchDialogVm.batchList[index].Counts;
            batchDialogVm.batchList[index].SelectedCount = count;
          }
          setCardsNumber(batch, count);
          batchDialogVm.batchList[index].SelectedCardNumberList = batch.SelectedCardNumberList;
        },

        handleCradsInput: function (e) { // 输入选择卡片的改变事件

          var index = parseInt(e.target.parentNode.getAttribute('data_index'));
          var batch = batchDialogVm.batchList[index];
          var cardNumArr = batch.SelectedCardNumberList.split(',');
          var cardNumber = batch.cardsNumber;
          var careNumberArr = cardNumber.split(',');

          if (!batch.cardsNumber) {
            batch.SelectedCardNumberList = '';
            return;
          }

          // 第一步 判断count 是否为0
          if (parseInt(batchDialogVm.batchList[index].SelectedCount) === 0) {
            batchDialogVm.batchList[index].SelectedCardNumberList = '';
            return;
          }

          if (cardNumArr.length > careNumberArr.length) {
            setCardsNumber(batch, careNumberArr.length);
            batchDialogVm.batchList[index].SelectedCardNumberList = batch.SelectedCardNumberList;
            return;
          }

          (function () {

            for (var i = 0; i < parseInt(batchDialogVm.batchList[index].SelectedCount); i++) {
              if (!batch.cardObj[cardNumArr[i]]) {
                if (i < careNumberArr.length) {
                  cardNumArr[i] = careNumberArr[i];
                }
              }
            }
            batchDialogVm.batchList[index].SelectedCardNumberList = cardNumArr.join(',');
          }());
        }
      };
    };

    // 保存转移单
    function saveTransferBill(batchDialogVm, chooseGoods, isSend) {
      // 首先检查 出库科室 和 入库科室 是否一样
      if (InputDeptAccount.DeptAccountID === OutDeptAccount.DeptAccountID) {
        if (InputTransferBillError) {
          InputTransferBillError();
        }
        tools.alterError('入库科室和出库科室不能是同一个科室');
        return;
      }

      // 检查是否每一个物品的批次信息是否对应
      var hasErrorForBatch = checkApplyCount(batchDialogVm, chooseGoods);

      if (hasErrorForBatch) {
        if (InputTransferBillError) {
          InputTransferBillError();
        }
        tools.alterError("选择的数量与申请的数量不一致！");
        return;
      }

      // 批次信息
      var batchSelections = [];
      for (var i = 0; i < chooseGoods.length; i++) {
        var batchWithCounts = [];
        chooseGoods[i].BatchList.forEach(function (data) {
          if (data.SelectedCount > 0) {
            var batchWithCount = {};
            batchWithCount.Price = data.CurrentPrice;
            batchWithCount.Count = data.SelectedCount;
            batchWithCount.BatchSN = data.BatchSN;
            batchWithCount.CardNumberList = data.SelectedCardNumberList;
            batchWithCount.Amount = batchWithCount.Count * batchWithCount.Price;
            batchWithCounts.push(batchWithCount);
          }
        });
        batchSelections[i] = {};
        batchSelections[i].Index = i + 1;
        batchSelections[i].Items = batchWithCounts;
      }
      InputTransferBill(chooseGoods, batchSelections, isSend);
    }

    // 检测选择的数量和申请的数量是否一致
    function checkApplyCount(batchDialogVm, chooseGoods) {
      var hasErrorForBatch = false;
      var i = 0;
      chooseGoods.forEach(function (data) {
        var ApplyNum = parseInt(data.ApplyNum);
        var sum = 0;

        data.BatchList.forEach(function (batch) {
          sum += batch.SelectedCount;
        });
        if (ApplyNum !== sum) {
          hasErrorForBatch = true;
          batchDialogVm.chooseGoods[i].hasErrorForBatch = true;
        } else {
          batchDialogVm.chooseGoods[i].hasErrorForBatch = false;
        }
        i++;
      });
      return hasErrorForBatch;
    }

    var compare = function (pre, next) {
      if (parseInt(pre.BatchSN) > parseInt(next.BatchSN)) {
        return 1;
      } else if (parseInt(pre.BatchSN) < parseInt(next.BatchSN)) {
        return -1;
      } else {
        return 0;
      }
    };

    // 设置 number
    function setCardsNumber(data, applyNum) {
      // 生成 卡片名称 xxx,xxx
      if (!data.cardsNumber) {
        var cardsNumber = '';
        var cardObj = {};
        if (data.Cards) {
          (function () {
            for (var i = 0; i < data.Cards.length; i++) {
              if (i !== data.Cards.length - 1) {
                cardsNumber += data.Cards[i].CardNumber + ',';
              } else {
                cardsNumber += data.Cards[i].CardNumber;
              }
              cardObj[data.Cards[i].CardNumber] = data.Cards[i].CardNumber;
            }
            data.cardObj = cardObj;
          }())
        }
        data.cardsNumber = cardsNumber;
      }

      // 按照流水号排序
      if (data.Cards) {
        data.Cards.sort(compare);
      }
      //
      data.SelectedCardNumberList = data.SelectedCardNumberLis || '';
      if (applyNum > data.Counts) {
        data.SelectedCount = data.Counts;
        data.SelectedCardNumberList = cardsNumber || '';
        applyNum -= data.Counts;

      } else if (applyNum !== 0 && applyNum <= data.Counts) {
        data.SelectedCount = applyNum;
        (function () {
          var cardNumber = '';
          if (data.Cards) {
            for (var i = 0; i < applyNum; i++) {
              if (i !== applyNum - 1) {
                cardNumber += data.Cards[i].CardNumber + ',';
              } else {
                cardNumber += data.Cards[i].CardNumber;
              }
            }
          }
          data.SelectedCardNumberList = cardNumber || '';
        }());
        applyNum = 0;
      }

      data.DetailRemark = data.DetailRemark || '';
      return applyNum;
    }

    // get batch info isInit 是否是初次加载 初次加载的话 可以将其 显示出来
    function initBatchInfo(index, good, OutDeptAccount, loadingIndex, length) {
      var param = {
        className: 'StoreBatchManager',
        method: 'GetBatchLayoutWithCards',
        goodsID: good.GoodsID,
        deptAccountID: OutDeptAccount.DeptAccountID,
        showZeroBatch: false,
        matchPrice: false,
        price: 0
      };
      api.getBatchLayoutWithCards(param)
        .then(function (jsonResult) {

          if (jsonResult.issuccess !== 0) {
            return Promise.reject(jsonResult.message);
          }

          var result = JSON.parse(jsonResult.result);
          var applyNum = parseInt(good.ApplyNum); //

          // 修改的话 同样 初始化
          result.forEach(function (data) {
            applyNum = setCardsNumber(data, applyNum);
          });

          // 将其保存在 商品列表中 方便获取
          chooseGoods[index].BatchList = result;
          if (index === 0) {
            batchDialogVm.batchList.splice(0, batchDialogVm.batchList.length);
            batchDialogVm.batchList.pushArray(result);
          }

          if (length && index === (length - 1)) {
            layer.close(loadingIndex);
          }
        })['catch'](function (ex) {
          layer.close(loadingIndex);
          tools.handleError(ex);
        });
    }

    var init = function (param) {
      api = param.api;
      chooseGoods = param.goodsInfo;
      layeroObj = tools.createNewOpenWindow(['800px', '560px'], '批次选择', htmlTemp);
      batchDialogVm = tools.initAvalonVm(avalon, getVmOption(), '.batch-select-dialog');

      batchDialogVm.chooseGoods.splice(0, batchDialogVm.chooseGoods.length);
      batchDialogVm.chooseGoods.pushArray(param.goodsInfo); // 选择的商品信息
      InputTransferBillError = param.InputTransferBillError;
      InputTransferBill = param.InputTransferBill;

      BillStatus = param.BillStatus;
      isSend = param.isSend;

      // 这里需要判断 转移单 出库科室为当前登录科室
      OutDeptAccount.DeptAccountID = param.OutDeptAccountID ||
        JSON.parse(localStorage.getItem('deptInfo')).DeptAccountID;
      InputDeptAccount.DeptAccountID = param.InputDepAccountID;

      // 加载所有的批次信息
      var loadingIndex = layer.load(); // 加载
      for (var i = 0; i < chooseGoods.length; i++) {
        initBatchInfo(i, chooseGoods[i], OutDeptAccount, loadingIndex, chooseGoods.length);
      }
    };

    return {
      init: init
    }
  });